<template>
  <div class="inputNumber">
    <el-row>
      <el-col :span="11">
        <el-input
          v-model="numFrom"
          placeholder="整数"
          v-enter-number
          @input="handleValue"
        ></el-input>
      </el-col>
      <el-col :span="2"><span class="line">~</span></el-col>
      <el-col :span="11">
        <el-input
          v-model="numTo"
          placeholder="整数"
          v-enter-number
          @input="handleValue"
        ></el-input>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'inputNumber',
  inheritAttrs: false,
  props: {
    type: {
      type: String,
      default: () => {}
    }
  },
  data() {
    return {
      numFrom: '',
      numTo: '',
      numWeight: []
    }
  },
  directives: {
    enterNumber: {
      inserted: function(el) {
        el.addEventListener('keypress', function(e) {
          e = e || window.event
          let charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode
          let re = /\d/
          if (
            !re.test(String.fromCharCode(charcode)) &&
            charcode > 9 &&
            !e.ctrlKey
          ) {
            if (e.preventDefault) {
              e.preventDefault()
            } else {
              e.returnValue = false
            }
          }
        })
      }
    }
  },
  methods: {
    handleValue() {
      this.numWeight = [this.numFrom, this.numTo]
      let params
      switch (this.type) {
        case '15':
          params = {
            mediaWeightFrom: this.numFrom,
            mediaWeightTo: this.numTo,
            mediaWeight: this.numWeight
          }
          break
      }
      this.setNewFormData(params)
    },
    init() {
      switch (this.type) {
        case '15':
          this.numFrom = this.formData.mediaWeightFrom
          this.numTo = this.formData.mediaWeightTo
          this.numWeight = this.formData.mediaWeight
          break
      }
    },
    ...mapMutations('charts', ['setNewFormData'])
  },
  computed: {
    ...mapState('charts', ['formData', 'resetFormData'])
  },
  mounted() {
    this.init()
  },
  watch: {
    resetFormData() {
      this.init()
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
  display: block;
}
</style>
